#!/bin/bash

root=$(dirname $(dirname $0))
dist="$root/heroic-dist"

JVM_OPTS=${JVM_OPTS:-""}

GRADLE=${GRADLE:-./gradlew}
GRADLE_OPTS=${GRADLE_OPTS:-"--console=plain"}
DIST_TASK="heroic-dist:shadowJar"

dist_jar="$dist/build/libs/heroic-dist-0.0.1-SNAPSHOT-shaded.jar"
CLASSPATH="$dist_jar"

if [[ $1 == '-debug' ]]; then
    JVM_OPTS="$JVM_OPTS -agentlib:jdwp=transport=dt_socket,server=y,address=5005,suspend=y"
    JVM_OPTS="$JVM_OPTS -Dloglevel=TRACE"
    shift
fi

if [[ -d $dist ]]; then
    if [[ ! -f $dist_jar ]]; then
        (cd $root && $GRADLE $GRADLE_OPTS clean $DIST_TASK)
    fi

    if [[ ! -f $dist_jar ]]; then
        echo "No such jar: $dist_jar" 1>&2
        exit 1
    fi
fi

exec java -cp "$CLASSPATH" $JVM_OPTS com.spotify.heroic.HeroicShell "$@"
